package com.jolink.omiis.wechat.outer;

import java.util.Map;

import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jolink.omiis.wechat.WeChatContext;
import com.jolink.omiis.wechat.crypt.aes.AesException;
import com.jolink.omiis.wechat.inner.IOmiisMessager;
import com.jolink.omiis.wechat.keys.IPreferences;
import com.jolink.omiis.wechat.message.AbstractMessageHandler;
import com.jolink.omiis.wechat.message.MessageHandlerFactory;
import com.jolink.omiis.wechat.message.type.UserType;

/**
 * @author WangYanqing
 *
 */
public class MessageWorker implements Runnable {
	private static Logger logger = LoggerFactory.getLogger(MessageWorker.class);
	private WeChatContext context;
	private String reqMessage;
	private Map<String, String[]> reqParams;
	private IOmiisMessager messager;

	public MessageWorker(WeChatContext context, Map<String, String[]> reqParams, String reqMessage,
			IOmiisMessager messager) {
		this.context = context;
		this.reqParams = reqParams;
		this.reqMessage = reqMessage;
		this.messager = messager;
	}

	@SuppressWarnings("static-access")
	@Override
	public void run() {
		AbstractMessageHandler messageHandler = null;
		Map<String, String> componentInfo = context.getCompentInfo();
		logger.info("三方平台信息：{}，请求参数：{}，请求信息：{}：", componentInfo, reqParams, reqMessage);
		String app_id = componentInfo.get(IPreferences.COMPONENT_APP_ID);
		String token = componentInfo.get(IPreferences.TOKEN);
		String encrypt_key = componentInfo.get(IPreferences.ENCRYPT_KEY);
		String msg_signature = reqParams.get("msg_signature")[0];
		String timestamp = reqParams.get("timestamp")[0];
		String nonce = reqParams.get("nonce")[0];
		try {
			Assert.assertNotNull("appId为空", app_id);
			Assert.assertNotNull("token为空", token);
			Assert.assertNotNull("encrypt_key为空", encrypt_key);
			Assert.assertNotNull("msg_signature为空", msg_signature);
			Assert.assertNotNull("timestamp为空", timestamp);
			Assert.assertNotNull("nonce为空", nonce);
		} catch (AssertionError e) {
			logger.error(e.getMessage(), e);
			return;
		}
		UserType userType;
		if (reqMessage.contains(UserType.AppId.getValue())) {
			userType = UserType.AppId;
		} else if (reqMessage.contains(UserType.ToUserName.getValue())) {
			userType = UserType.ToUserName;
		} else {
			logger.error("未知的消息类型！");
			return;
		}
		ICrypt crypt = null;
		String resultMsg = null;
		try {
			logger.info("消息发送方类型：{}，密文信息：{}，开始解密请求信息......", userType.getValue(), reqMessage);
			crypt = new Crypt(token, encrypt_key, app_id);
			resultMsg = crypt.decrypt(msg_signature, timestamp, nonce, reqMessage, userType);
			logger.info("解密完成，请求内容：{}。", resultMsg);
		} catch (AesException e) {
			logger.error(e.getMessage(), e);
		}
		messageHandler = (AbstractMessageHandler) MessageHandlerFactory.getInstance()
				.createMessageHandler(userType.getValue());
		messageHandler.setReqMessage(resultMsg);
		messageHandler.setReqParams(reqParams);
		messageHandler.setContext(context);
		messageHandler.setMessager(messager);
		try {
			messageHandler.handleMessage();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
}
